﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DddCms.Domain.Repository;
using DddCms.Domain.Model;
using Microsoft.Practices.Unity;
using DddCms.Domain.Utility;

namespace DddCms.Domain.Factory
{
    public interface IUserFactory
    {
        bool CreateUser(
            string username,
            string password,
            string email,
            string passwordQuestion,
            string passwordAnswer);

        bool AlreadyExist(string username);
    }


    public class UserFactory : IUserFactory
    {
        /// <summary>
        /// 
        /// </summary>
        [Dependency]
        public IRepository Repository { get; set; }
     
        /// <summary>
        /// 
        /// </summary>
        [Dependency]
        public IPasswordUtil PasswordUtil { get; set; }

        /// <summary>
        /// 
        /// </summary>
        [Dependency]
        public ILoggingUtil LoggingUtil { get; set; }

        public bool CreateUser(
            string username,
            string password,
            string email,
            string passwordQuestion,
            string passwordAnswer)
        {
            if (String.IsNullOrEmpty(username)) throw new ArgumentNullException("username");
            if (String.IsNullOrEmpty(password)) throw new ArgumentNullException("password");
            if (String.IsNullOrEmpty(password)) throw new ArgumentNullException("email");
            if (String.IsNullOrEmpty(password)) throw new ArgumentNullException("passwordQuestion");
            if (String.IsNullOrEmpty(password)) throw new ArgumentNullException("passwordAnswer");


            if (Repository.Users.AlreadyExist(username)) return false;


            User user = new User()
            {
                UserName = username,
                Password = PasswordUtil.encryption(password),
                Email = email,
                PasswordQuestion = passwordQuestion,
                PasswordAnswer = passwordAnswer,
                Roles = new List<Role>() { Repository.Roles.Single(r => r.Name == "user") }
            };

            Repository.Users.Add(user);

            LoggingUtil.Information("UserFactory", "Create User", "Nouvelle utilisateur : " + username);

            return true;
        }

        public bool AlreadyExist(string username)
        {
            return Repository.Users.Any(user => user.UserName == username);
        }
    }
}
